import stat from '@lib/api/stat';

declare global {
	interface Window {
		_hmt?: any[];
	}
}

class repeatCheck {
	private repeat: string[];
	private name: string;
	constructor(name: string) {
		this.name = name;
		if (typeof (window) === "undefined") {
			this.repeat = [];
			return;
		}
		let passed = false;
		try {
			passed = 'sessionStorage' in window && window.sessionStorage != null;
		} catch (e) {
			/* If we get a security exception we know the feature exists, but cookies are disabled */
		}
		if (!passed) {
			this.repeat = [];
			return;
		}
		const res = window.sessionStorage.getItem(name);
		if (res) {
			this.repeat = res.split(',');
		} else {
			this.repeat = [];
		}
	}
	has(id: string): boolean {
		return this.repeat.includes(id);
	}
	add(id: string) {
		this.repeat.push(id);
		try {
			window.sessionStorage.setItem(this.name, this.repeat.join(','));
		} catch (e) {
			console.log(e);
		}
	}
}

const trackedClick = new repeatCheck("tracked_click");
const trackedCopy = new repeatCheck("tracked_copy");

export function doTrack(event: string, type: string, label?: any) {
	if (typeof (window) === "undefined") return;
	if (typeof (window._hmt) === "undefined") {
		window._hmt = [];
	}
	window._hmt.push(['_trackEvent', event, type, label]);
}

export function page(url: string) {
	if (typeof (window) === "undefined") return;
	if (typeof (window._hmt) === "undefined") {
		window._hmt = [];
	}
	window._hmt.push(['_trackPageview', url]);
}

export function click(id: number) {
	const strid = id.toString();
	if (!trackedClick.has(strid)) {
		stat({
			action: "click",
			id: id
		});
		trackedClick.add(strid);
	}
}

export function copy(type: string, id: number) {
	doTrack('copy', type, id);
	if (type === "code" && !trackedCopy.has(id.toString())) {
		stat({
			action: "copy",
			id
		});
		trackedCopy.add(id.toString());
	}
}

export function share(platform: string, id: number) {
	doTrack("share", platform, id);
	stat({
		action: "share",
		id
	});
}

export function vote(id: number) {
	stat({
		action: "vote",
		id
	});
}